//
// Created by RandBII on 2020/12/24.
//

#include "NativeRender.h"

NativeRender::NativeRender(JNIEnv *evn, jobject surface) : VideoRender(VIDEO_RENDER_ANWINDOW) {
    mNativeWindow = ANativeWindow_fromSurface(evn, surface);
}

NativeRender::~NativeRender() {
    if (mNativeWindow) ANativeWindow_release(mNativeWindow);
}

void NativeRender::Init(int videoWidth, int videoHeight, int *dstSize) {
    LOG_D("ANativeWindow  %p", "videoWidth: %d", "videoHeight: %d", "dstSize: %d",
          mNativeWindow,
          videoWidth,
          videoHeight,
          dstSize);
    if (mNativeWindow == nullptr) return;
    int windowWidth = ANativeWindow_getWidth(mNativeWindow);
    int windowHeight = ANativeWindow_getHeight(mNativeWindow);

    // 屏幕的宽高比  < 视频的宽高比
    if (windowWidth < windowHeight * videoWidth / videoHeight) {
        mDstWidth = windowWidth;
        mDstHeight = windowHeight * videoHeight / videoWidth;
    } else {
        mDstHeight = windowHeight;
        mDstWidth = windowWidth * videoWidth / videoHeight;
    }

    dstSize[0] = mDstWidth;
    dstSize[1] = mDstHeight;


}

void NativeRender::RenderVideoFrame(NativeImage *pImage) {

    if (mNativeWindow == nullptr || pImage == nullptr) {
        LOG_E("NativeRender::RenderVideoFrame mNativeWidow %p", "NativeImage %p",
              mNativeWindow, pImage);
        return;
    }

    ANativeWindow_lock(mNativeWindow, &mNativeWindowBuffer, nullptr);
    auto *dstBuffer = static_cast<uint8_t *>(mNativeWindowBuffer.bits);
// RGBA 一行的像素占用的内存空间
    int srcLineSize = pImage->width * 4;

//     The number of *pixels* that a line in the buffer takes in memory
    int dstLineSize = mNativeWindowBuffer.stride * 4;

    // 一帧图像占用内存的空间
    for (int i = 0; i < mDstHeight; ++i) {
        memcpy(dstBuffer + i * dstLineSize, pImage->ppPlane[0] + i * srcLineSize, srcLineSize);
    }

    //LOG_E("dst dstLineSize %d", dstLineSize);
    ANativeWindow_unlockAndPost(mNativeWindow);

}

void NativeRender::UnInit() {

}




